package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.domain.*;
import com.atguigu.service.OrderItemService;
import com.atguigu.service.OrderService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author dl
 * @date 2020/5/4 15:26
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();

    private OrderItemService orderItemService = new OrderItemServiceImpl();

    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String checkout(Cart cart, User user) {
        // 1 create order id
        long timeMillis = System.currentTimeMillis();
        String orderId = timeMillis + "" + user.getId();
        // 2 encapsulation order object
        Order order = new Order(orderId, new Date(), cart.getTotalAllMoney(), 0, user.getId());
        // encapsulation order_item object
        List<BookItems> items = cart.getItems();
        List<OrderItem> list = new ArrayList<>();
        for (BookItems item : items) {
            OrderItem orderItem = new OrderItem(item.getBook().getName(), item.getPrice(), item.getTotalMoney(), item.getCount(), orderId);
            list.add(orderItem);
        }
        // 3 save order and order_item
        int save = orderDao.save(order);
        // save order item
        orderItemService.saveOrderItem(list);
        // 4 update book sales and stock
        for (BookItems bookItems : items) {
            Book bookById = bookDao.getBookById(bookItems.getBook().getId());
            int count = bookItems.getCount();
            bookById.setStock(bookById.getStock() - count);
            bookById.setSales(bookById.getSales() + count);
            bookDao.updateBook(bookById);
        }
        cart.clear();
        return orderId;
    }

    @Override
    public void update(String orderId, String status) {
        Order order = new Order();
        order.setOrderId(orderId);
        int orderStatus = 0;
        try {
            orderStatus = Integer.parseInt(status);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        order.setStatus(orderStatus);
        orderDao.update(order);
    }

    @Override
    public List<Order> listOrders() {
        return orderDao.listOrders();
    }

    @Override
    public List<Order> getOrder(String userId) {
        return orderDao.getOrderByUserId(userId);
    }
}
